<template>
  <el-popover
    :placement="popoverPlacement"
    :title="popoverTitle"
    :width="popoverWidth"
    :trigger="popoverTrigger"
    >
    <el-switch
     v-model="currentValue"
     :active-text="switchActiveText"
     :inactive-text="switchInactiveText"
     :active-value="switchActiveValue"
     :inactive-value="switchInactiveValue"
     @change="handleChange" />
    <span slot="reference">
      <el-tag v-if="value == 1" size="small" type="danger">禁用</el-tag>
      <el-tag v-else size="small">正常</el-tag>
    </span>
  </el-popover>
</template>

<script>
export default {
  props: {
    value: {
      default: 0
    },
    userId: {
      default: 0
    },
    popoverPlacement: {
      default: 'left'
    },
    popoverTitle: {
      default: '切换状态'
    },
    popoverWidth: {
      default: 200
    },
    popoverTrigger: {
      default: 'hover'
    },
    switchActiveText: {
      default: '启用'
    },
    switchInactiveText: {
      default: '禁用'
    },
    switchActiveValue: {
      default: 0
    },
    switchInactiveValue: {
      default: 1
    }
  },
  data () {
    return {
      currentValue: 0,
      disabled: false
    }
  },
  watch: {
    value: {
      handler (val) {
        this.currentValue = val
      },
      immediate: true
    }
  },
  methods: {
    handleChange (val) {
      this.disabled = true
      this.$http({
        url: this.$http.adornUrl(`/sys/user/changeStatus/${this.userId}/${this.currentValue}`),
        methods: 'post'
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.disabled = false
          this.$message({
            message: '修改成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.$emit('refreshDataList')
            }
          })
        } else {
          this.$message.error('切换失败,请稍后重试')
        }
      })
    }
  }
}
</script>

